package com.csst.util;
import java.lang.reflect.Array;

public class MD5 {
	/**
	 * 计算字符串的MD5值
	 * @param string 字符串
	 * @return 
	 */
	public static String getMD5(String string) {
		return getMD5(string.getBytes());
	}
	
	/**
	 * 计算byte数组的MD5值
	 * @param source
	 * @return 该byte数组的MD5值
	 */
	public static String getMD5(byte[] source) {
		String s = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest();
			char str[] = new char[16 * 2];
			int k = 0;
			for (int i = 0; i < 16; i++) {
				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			s = new String(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}

	public static void main(String args[]) {
		if (Array.getLength(args) == 0) { // 如果没有参数，执行标准的Test Suite
			System.out.println("MD5 Test suite:");
			System.out.println("MD5(\"\"):" + MD5.getMD5(""));
			System.out.println("MD5(\"SUPER-share\"):" + MD5.getMD5("SUPER-share"));
			System.out.println("MD5(\"a\"):" + MD5.getMD5("a"));
			System.out.println("MD5(\"abc\"):" + MD5.getMD5("abc"));
			System.out.println("MD5(\"message digest\"):" + MD5.getMD5("message digest"));
			System.out.println("MD5(\"abcdefghijklmnopqrstuvwxyz\"):" + MD5.getMD5("abcdefghijklmnopqrstuvwxyz"));
			System.out.println("MD5(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"):" + MD5.getMD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"));
			System.out.println("MD5(\"123\"):" + MD5.getMD5("123"));
		} else
			System.out.println("MD5(" + args[0] + ")=" + MD5.getMD5(args[0]));

	}

}
